//
//  FriendVC.m
//  RPay
//
//  Created by hzy on 2017/10/29.
//  Copyright © 2017年 Charlie. All rights reserved.
//

#import "FriendVC.h"
#import "FriendServers.h"
#import "RefreshManager.h"
#import "FriendModel.h"
#import "FriendCell.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "SendRedPacketVC.h"
#import "AddFriendView.h"

@interface FriendVC ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *searchTextF;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)RefreshManager * refreshManager;
@property (nonatomic,strong)NSMutableArray * dataSource;

@end

@implementation FriendVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"好友";
    [self addNavigationBarLeftButtonItem];
    [self addRightButtonItem];
    [self setupUI];
    [self network];
    [_searchTextF addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];

}

-(void)addRightButtonItem{
    
    UIButton * leftBarButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBarButton.frame = CGRectMake(0, 0, 30, 40);
    [leftBarButton addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [leftBarButton setTitle:@"+" forState:0];

    leftBarButton.titleLabel.font = [UIFont systemFontOfSize:22];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:leftBarButton];
    self.navigationItem.rightBarButtonItem = item;


}
-(void)addBtnClick{

    AddFriendView * view = [[[NSBundle mainBundle] loadNibNamed:@"AddFriendView" owner:nil options:nil] lastObject];
    view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));

    
    view.sureBlock = ^(NSString *string){
    
        if (string.length) {
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [[TMNetwork sharedInstance] POSTWithJSONRequestSerialized:@"/open/appRedPacket/addFriend.shtml" headerParams:nil queryParams:nil formParams:@{@"userNumber":[ShareUser shareUser].userName,@"friendNumber":string} withToken:NO model:nil progress:^(NSProgress *progress) {
                
            } success:^(id responseObject) {
                if ([responseObject[@"code"] integerValue] == 200) {
                    [self alertWithTitle:@"添加成功" message:nil handler:NULL];
                    [_refreshManager.headerView beginRefreshing];
                }else{
                    
                    [self alertWithTitle:responseObject[@"msg"] message:nil handler:NULL];
                }
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                
                
                
                
                
            } failure:^(id responseObject) {
                [self alertNetworkError];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
        }else{
        
            [self alertWithTitle:@"提示" message:@"请输入用户名" handler:nil];
        }
        
        
        
    };
    
    [self.view addSubview:view];
    

    
    

}
-(void)setupUI{

    _searchTextF.delegate  =self;
    if (_type != FriendList) {
        
        [self addNavigationBarRightButtonItemWithInfo:@"发送" target:self action:@selector(sendRedpacket)];
        
    }
    
    
    

}
-(void)textFieldChanged:(UITextField *)textField{

    if (!textField.text.length) {
        _refreshManager.isPost = NO;
        _refreshManager.urlstring = @"/open/appRedPacket/getFriendList.shtml?";
        _refreshManager.formParams = [NSMutableDictionary dictionaryWithDictionary:@{@"userNumber":[ShareUser shareUser].userName,@"type":@"system"}];
        [_refreshManager.headerView beginRefreshing];
    }
    
    

}
-(void)sendRedpacket{

    NSMutableArray * array = [NSMutableArray array];
    
    for (FriendModel * model in _dataSource) {
        
        if (model.selected == YES) {
            [array addObject:model];
            
        }
        
    }
    if (!array.count) {
        [self alertWithTitle:@"温馨提示" message:@"您尚未选择好友！" handler:NULL];
    }else{
        NSString * userStr = @"";
        
        for (FriendModel * model  in array) {
            userStr = [NSString stringWithFormat:@"%@,%@",model.friendNumber,userStr];
        }
        
        SendRedPacketVC * vc = [[SendRedPacketVC alloc] initWithNibName:@"SendRedPacketVC" bundle:[NSBundle mainBundle]];
        
        vc.isSingle = (_type == SingleRedPacket);
        
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        [dic setObject:@(array.count) forKey:@"redPacketCount"];
        [dic setObject:userStr forKey:@"receiver"];
        [dic setObject:@"random" forKey:@"type"];
        vc.pamas = dic;
        [self.navigationController pushViewController:vc animated:YES];
        
        
        
    
    
        
    
    }


}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    
    if (textField.text.length) {
        
        _refreshManager.isPost = YES;
        _refreshManager.urlstring = @"/open/appRedPacket/searchFriend.shtml";
        _refreshManager.formParams = [NSMutableDictionary dictionaryWithDictionary:@{@"userNumber":[ShareUser shareUser].userName,@"friendNumber":textField.text}];
        
        [_refreshManager.headerView beginRefreshing];
    }
    
    
    
    return YES;
}
-(void)network{
    MJWeakSelf
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _tableView.dataSource = self;
    _tableView.delegate  =self;
    _dataSource = [NSMutableArray array];
    _refreshManager = [[RefreshManager alloc] initWithurl:@"/open/appRedPacket/getFriendList.shtml?" Params:@{@"userNumber":[ShareUser shareUser].userName}];

    _refreshManager.headerCompleteBlock = ^(id responseObject) {
        NSLog(@"%@",responseObject);
        [weakSelf.dataSource removeAllObjects];
        [weakSelf refeshData:responseObject[@"page"]];
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
    };
    _refreshManager.footerCompleteBlock = ^(id responseObject) {
        
//        if ([weakSelf.refreshManager.urlstring isEqualToString:@"/open/appRedPacket/searchFriend.shtml"]) {
//            [weakSelf.dataSource removeAllObjects];
//        }
        
         [weakSelf refeshData:responseObject[@"page"]];
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    };
    [_refreshManager setRefreshHeader:_tableView];
    [_refreshManager setRefreshfooter:_tableView];

    [_refreshManager.headerView beginRefreshing];
    

}

-(void)refeshData:(NSArray *)array{
    
    NSArray * modelArr = [FriendModel mj_objectArrayWithKeyValuesArray:array];
    
    [_dataSource addObjectsFromArray:modelArr];
    [_tableView reloadData];
    

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return  _dataSource.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 40;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static  NSString  *CellIdentiferId = @"FriendCell";
    FriendCell  *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentiferId];
    if (cell == nil) {
        NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"FriendCell" owner:nil options:nil];
        cell = [nibs lastObject];
        cell.backgroundColor = [UIColor clearColor];
    };
    
    FriendModel * model = _dataSource[indexPath.row];
    cell.nameLab.text = model.friendNumber;
    cell.nickLab.text = model.friendNeckName;
    if (_type == FriendList) {
        cell.selectBtn.hidden = YES;
    }else{
    
        cell.selectBtn.selected = model.selected;
    }
    
    return cell;
}
-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{

    return _type != FriendList;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [_tableView deselectRowAtIndexPath:indexPath animated:YES];
    FriendModel * model = _dataSource[indexPath.row];
    
    if (_type == SingleRedPacket) {
        
        for (FriendModel * mod in _dataSource) {
            mod.selected = NO;
        }
        
        
        model.selected = YES;
    }else if (_type == GroupRedPacket){
    
        model.selected = !model.selected;
    }
    
    [_tableView reloadData];
    



}

@end
